package com.njupt.swg.controller;

import com.njupt.swg.constants.Constant;
import com.njupt.swg.resp.UploadResp;
import com.njupt.swg.utils.JsonUtils;
import com.njupt.swg.utils.QiniuFileUploadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {
    @RequestMapping("/pic/upload")
    @ResponseBody
    public String uploadHeadImg(@RequestParam(required=false) MultipartFile uploadFile) {
        Logger logger = LoggerFactory.getLogger(UploadController.class);
        UploadResp resp = new UploadResp();
        try {
            String originFilename = uploadFile.getOriginalFilename();
            String extName = originFilename.substring(originFilename.lastIndexOf(".")+1);
            String imgUrlName = QiniuFileUploadUtil.uploadHeadImg(uploadFile);
            String url = Constant.QINIU_HEAD_IMG_BUCKET_URL+imgUrlName;
            resp.setError(0);
            resp.setUrl(url);
            return JsonUtils.objectToJson(resp);
        }  catch (Exception e) {
            resp.setError(1);
            resp.setMessgae("图片上传失败");
            logger.error("上传失败",e);
            return JsonUtils.objectToJson(resp);
        }
    }
}
